import { apiPay, apiOrderBindBalance, apiAppletWechatPay } from '../../api/index'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    outTradeNo: '',
    orderId: '',
    memberBalance: 0,
    need_pay_money: 0,
    isUseBalance: false,
    goodData: [],
    makeMoney: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    if (options.help_type) {
      this.helpType = 1
    }
    this.data.orderId = options.id
    this.getPayMsg(options)
  },
  getPayMsg (options) {
    if (options.out_trade_no) {
      apiPay({
        out_trade_no: options.out_trade_no
      }).then(res => {
        console.log(res)
        let data = res.data
        this.setData({
          orderData: res.data.pay_value,
          outTradeNo: options.out_trade_no,
          orderId: options.id,
          memberBalance: data.member_balance,
          need_pay_money: (data.need_pay_money - 0).toFixed(2)
        })
      })
    } else {
      apiPay({
        order_id: options.id
      }).then(res => {
        console.log(res)
        this.setData({
          orderData: res.data.pay_value,
          outTradeNo: res.data.pay_value.out_trade_no,
          orderId: options.id,
          memberBalance: res.data.member_balance,
          need_pay_money: (res.data.need_pay_money - 0).toFixed(2)
        })
      }).catch(() => {
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1300)
      })
    }
  },
  switchChange (e) {
    console.log(e.detail.value)
    this.setData({
      isUseBalance: e.detail.value
    })
  },
  toPay () {
    if (this.data.isUseBalance && (this.data.need_pay_money - 0) === 0) {
      wx.showModal({
        title: '提示',
        content: '确认使用余额支付',
        success: (suc) => {
          if (suc.confirm) {
            apiOrderBindBalance({
              out_trade_no: this.data.outTradeNo,
              is_use_balance: this.data.isUseBalance ? 1 : 0
            }).then(res => {
              console.log(res)
              switch (Number(res.data.code)) {
                case 0:
                  // 余额不足，调用微信支付
                  this.getPayAssess()
                  break
                case 1:
                  // 支付成功
                  if (this.helpType === 1) {
                    wx.redirectTo({
                      url: `../pay-sure/pay-sure?id=${this.data.orderId}&help_type=1`
                    })
                  } else {
                    wx.redirectTo({
                      url: `../pay-sure/pay-sure?id=${this.data.orderId}`
                    })
                  }
                  break
                case -1:
                  // 支付失败
                  wx.showToast({
                    title: res.message,
                    icon: 'error',
                    mask: true
                  })
                  break
                default:
                  break
              }
            })
          } else {
            console.log(this.data.orderId)
            if (this.helpType === 1) {
              wx.redirectTo({
                url: `../order-detail/order-detail?id=${this.data.orderId}&help_type=1`
              })
            } else {
              wx.redirectTo({
                url: `../order-detail/order-detail?id=${this.data.orderId}`
              })
            }
          }
        }
      })
    } else {
      apiOrderBindBalance({
        out_trade_no: this.data.outTradeNo,
        is_use_balance: this.data.isUseBalance ? 1 : 0
      }).then(res => {
        console.log(res)
        switch (Number(res.data.code)) {
          case 0:
            // 余额不足，调用微信支付
            this.getPayAssess()
            break
          case 1:
            // 支付成功
            break
          case -1:
            // 支付失败
            wx.showToast({
              title: res.message,
              icon: 'error',
              mask: true
            })
            break
          default:
            break
        }
      })
    }
  },
  getPayAssess () {
    apiAppletWechatPay({
      out_trade_no: this.data.outTradeNo,
      openid: wx.getStorageSync('openid')
    }).then(res => {
      if (this.helpType === 1) {
        this.appHelpPay(res.data)
      } else {
        this.appletPay(res.data)
      }
    })
  },
  appHelpPay (datas) {
    let id = this.data.orderId
    wx.requestPayment({
      timeStamp: datas.timestamp.toString(),
      nonceStr: datas.nonce_str,
      package: 'prepay_id=' + datas.prepay_id,
      signType: 'MD5',
      paySign: datas.PaySign,
      success () {
        wx.redirectTo({
          url: `../pay-sure/pay-sure?id=${id}&help_type=1`
        })
      },
      fail (err) {
        wx.showToast({
          title: err.err_desc,
          icon: 'error',
          mask: true
        })
        wx.redirectTo({
          url: `../order-detail/order-detail?id=${id}&help_type=1`
        })
      }
    })
  },
  appletPay (datas) {
    let id = this.data.orderId
    wx.requestPayment({
      timeStamp: datas.timestamp.toString(),
      nonceStr: datas.nonce_str,
      package: 'prepay_id=' + datas.prepay_id,
      signType: 'MD5',
      paySign: datas.PaySign,
      success () {
        wx.redirectTo({
          url: `../pay-sure/pay-sure?id=${id}`
        })
      },
      fail (err) {
        wx.showToast({
          title: err.err_desc,
          icon: 'error',
          mask: true
        })
        wx.redirectTo({
          url: '../order-detail/order-detail?id=' + id
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {

  }
})
